package view;

import com.toedter.calendar.JDateChooser;
import model.Grade;
import model.Subject;
import model.User;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import service.GradeService;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import model.StudentProfile;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DatabaseUtil;
import java.awt.Color;

import org.jfree.chart.plot.PiePlot;

import java.sql.PreparedStatement;
import javax.swing.table.DefaultTableCellRenderer;

public class GradeAnalysisPanelTeacher extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);

    private User currentUser;
    private GradeService gradeService;
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private JPanel chartPanel;
    private ChartPanel barChartPanel;
    private ChartPanel pieChartPanel;
    private ChartPanel lineChartPanel;
    private JComboBox<String> classComboBox;
    private JComboBox<String> examTypeComboBox;
    private JDateChooser examDateChooser;
    private JTextField searchField;
    private JComboBox<String> sortComboBox;
    private Map<String, Integer> classIdMap = new HashMap<>();
    private boolean isClassTeacher = false;
    private List<Subject> classSubjects;
    private JPanel statsPanel;
    private JToggleButton viewToggleButton;
    private CardLayout cardLayout;
    private JPanel mainPanel;
    private JPanel classTeacherPanel;
    private JPanel teacherPanel;

    public GradeAnalysisPanelTeacher(User currentUser) {
        this.currentUser = currentUser;
        this.gradeService = new GradeService();
        // 检查是否是班主任
        checkClassTeacherRole();
        initComponents();
        loadData();
    }

    private void checkClassTeacherRole() {
        String sql = "SELECT c.id, c.class_name FROM classes c WHERE c.teacher_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, currentUser.getId());
            ResultSet rs = stmt.executeQuery();
            isClassTeacher = rs.next();
            if (isClassTeacher) {
                int classId = rs.getInt("id");
                System.out.println("Found class: " + rs.getString("class_name") + " (ID: " + classId + ")");
                // 获取班级的所有科目
                loadClassSubjects(classId);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void loadClassSubjects(int classId) {
        classSubjects = new ArrayList<>();
        String sql = "SELECT DISTINCT s.* FROM subjects s " +
                "JOIN grades g ON s.id = g.subject_id " +
                "JOIN students st ON g.student_id = st.id " +
                "JOIN classes c ON st.class_id = c.id " +
                "WHERE c.id = ? " +
                "ORDER BY s.subject_name";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, classId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Subject subject = new Subject();
                subject.setId(rs.getInt("id"));
                subject.setSubjectName(rs.getString("subject_name"));
                subject.setCredits(rs.getDouble("credits"));
                classSubjects.add(subject);
            }

            // 如果没有找到科目，尝试从 subject_teachers 表获取
            if (classSubjects.isEmpty()) {
                String backupSql = "SELECT DISTINCT s.* FROM subjects s " +
                        "JOIN subject_teachers st ON s.id = st.subject_id " +
                        "WHERE st.class_id = ? " +
                        "ORDER BY s.subject_name";
                try (PreparedStatement backupStmt = conn.prepareStatement(backupSql)) {
                    backupStmt.setInt(1, classId);
                    ResultSet backupRs = backupStmt.executeQuery();
                    while (backupRs.next()) {
                        Subject subject = new Subject();
                        subject.setId(backupRs.getInt("id"));
                        subject.setSubjectName(backupRs.getString("subject_name"));
                        subject.setCredits(backupRs.getDouble("credits"));
                        classSubjects.add(subject);
                    }
                }
            }

            // 打印日志，检查是否获取到科目
            System.out.println("Found " + classSubjects.size() + " subjects for class " + classId);
            for (Subject subject : classSubjects) {
                System.out.println("Subject: " + subject.getSubjectName());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void initComponents() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());

        // 创建筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));

        // 如果是班主任，添加视图切换按钮
        if (isClassTeacher) {
            viewToggleButton = new JToggleButton("切换到任教视图");
            viewToggleButton.addActionListener(e -> {
                if (viewToggleButton.isSelected()) {
                    viewToggleButton.setText("切换到班级视图");
                    cardLayout.show(mainPanel, "teacher");
                } else {
                    viewToggleButton.setText("切换到任教视图");
                    cardLayout.show(mainPanel, "classTeacher");
                }
                refreshData();
            });
            JPanel togglePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            togglePanel.add(viewToggleButton);
            topPanel.add(togglePanel, BorderLayout.EAST);
        }

        // 班级选择
        classComboBox = new JComboBox<>();
        if (!isClassTeacher) {
            classComboBox.addItem("全部班级");
            loadClasses();
        }

        // 考试类型选择
        examTypeComboBox = new JComboBox<>(new String[]{"全部", "期中考试", "期末考试", "单元测试", "模拟考试"});

        // 考试日期选择
        examDateChooser = new JDateChooser();
        examDateChooser.setDateFormatString("yyyy-MM-dd");

        // 搜索框
        searchField = new JTextField(15);
        searchField.setToolTipText("输入学号或姓名搜索");

        // 排序选择
        String[] sortOptions = isClassTeacher ?
                new String[]{"默认排序", "总分升序", "总分降序", "平均分升序", "平均分降序"} :
                new String[]{"默认排序", "成绩升序", "成绩降序", "排名升序", "排名降序"};
        sortComboBox = new JComboBox<>(sortOptions);

        // 添加到筛选面板
        if (!isClassTeacher) {
            filterPanel.add(new JLabel("班级:"));
            filterPanel.add(classComboBox);
        }
        filterPanel.add(new JLabel("考试类型:"));
        filterPanel.add(examTypeComboBox);
        filterPanel.add(new JLabel("考试日期:"));
        filterPanel.add(examDateChooser);
        filterPanel.add(new JLabel("搜索:"));
        filterPanel.add(searchField);
        filterPanel.add(new JLabel("排序:"));
        filterPanel.add(sortComboBox);

        // 添加刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshData());
        filterPanel.add(refreshButton);

        topPanel.add(filterPanel, BorderLayout.CENTER);
        add(topPanel, BorderLayout.NORTH);

        // 创建主面板使用卡片布局
        if (isClassTeacher) {
            cardLayout = new CardLayout();
            mainPanel = new JPanel(cardLayout);

            // 创建班主任视图和任教视图
            classTeacherPanel = createClassTeacherPanel();
            teacherPanel = createTeacherPanel();

            mainPanel.add(classTeacherPanel, "classTeacher");
            mainPanel.add(teacherPanel, "teacher");

            add(mainPanel, BorderLayout.CENTER);
            cardLayout.show(mainPanel, "classTeacher");
        } else {
            // 普通教师只有一个视图
            add(createTeacherPanel(), BorderLayout.CENTER);
        }

        // 添加监听器
        addListeners();

        // 添加搜索框监听器
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                refreshData();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                refreshData();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                refreshData();
            }
        });
    }

    private void addListeners() {
        // 添加筛选条件变化监听器
        classComboBox.addActionListener(e -> refreshData());
        examTypeComboBox.addActionListener(e -> refreshData());
        examDateChooser.getDateEditor().addPropertyChangeListener(e -> {
            if ("date".equals(e.getPropertyName())) {
                refreshData();
            }
        });
        sortComboBox.addActionListener(e -> refreshData());
    }

    private void refreshData() {
        if (isClassTeacher) {
            if (viewToggleButton.isSelected()) {
                loadNormalData(); // 加载任教视图数据
            } else {
                loadClassTeacherData(); // 加载班级视图数据
            }
        } else {
            loadNormalData();
        }
        updateStatistics(getFilters());
    }

    private void loadGradeData(Map<String, Object> filters, String orderBy) {
        // 清空表格
        tableModel.setRowCount(0);

        // 获取成绩数据
        List<Grade> grades = gradeService.getGrades(filters, orderBy);

        // 更新表格
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Grade grade : grades) {
            Object[] rowData = {
                    grade.getStudentNo(),
                    grade.getStudentName(),
                    grade.getClassName(),
                    grade.getSubjectName(),
                    grade.getScore(),
                    grade.getRank(),
                    String.format("%.2f", grade.getAverageScore()),
                    grade.getExamType(),
                    sdf.format(grade.getExamDate())
            };
            tableModel.addRow(rowData);
        }

        // 更新统计信息
        updateStatistics(filters);
    }

    @SuppressWarnings("unchecked")
    private void updateStatistics(Map<String, Object> filters) {
        // 获取统计数据
        Map<String, Object> stats = gradeService.getGradeStats(filters);

        // 更新统计标签
        updateStatsLabels(stats);

        // 更新图表
        updateCharts(stats);
    }

    private void loadData() {
        refreshData();
    }

    private void loadClasses() {
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT id, class_name FROM classes")) {

            while (rs.next()) {
                String className = rs.getString("class_name");
                int classId = rs.getInt("id");
                classComboBox.addItem(className);
                classIdMap.put(className, classId);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private ChartPanel createPieChartPanel() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        JFreeChart chart = ChartFactory.createPieChart(
                "成绩等级分布",      // 图表标题
                dataset,
                true,             // 显示图例
                true,             // 显示工具提示
                false             // 不生成URL
        );

        // 设置图表样式
        chart.setTitle(new TextTitle("成绩等级分布", new Font("微软雅黑", Font.BOLD, 14)));
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 设置饼图颜色
        plot.setSectionPaint("优秀", new Color(91, 155, 213));
        plot.setSectionPaint("良好", new Color(112, 173, 71));
        plot.setSectionPaint("不及格", new Color(237, 125, 49));

        // 设置图例字体
        chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(400, 300));
        return chartPanel;
    }

    private void updateCharts(Map<String, Object> stats) {
        if (stats == null) return;

        // 1. 更新饼图
        DefaultPieDataset pieDataset = new DefaultPieDataset();
        if (stats.containsKey("excellentCount") && stats.containsKey("passCount")) {
            int excellentCount = ((Number) stats.get("excellentCount")).intValue();
            int passCount = ((Number) stats.get("passCount")).intValue();
            int totalCount = ((Number) stats.get("totalCount")).intValue();
            int goodCount = passCount - excellentCount;
            int failCount = totalCount - passCount;

            if (excellentCount > 0) pieDataset.setValue("优秀(90-100)", excellentCount);
            if (goodCount > 0) pieDataset.setValue("良好(60-89)", goodCount);
            if (failCount > 0) pieDataset.setValue("不及格(0-59)", failCount);
        }

        if (pieChartPanel != null) {
            PiePlot piePlot = (PiePlot) pieChartPanel.getChart().getPlot();
            piePlot.setDataset(pieDataset);
        }

        // 2. 更新柱状图
        if (barChartPanel != null) {
            DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
            barDataset.setValue((Number) stats.get("range_90_100"), "人数", "90-100");
            barDataset.setValue((Number) stats.get("range_80_89"), "人数", "80-89");
            barDataset.setValue((Number) stats.get("range_70_79"), "人数", "70-79");
            barDataset.setValue((Number) stats.get("range_60_69"), "人数", "60-69");
            barDataset.setValue((Number) stats.get("range_0_59"), "人数", "0-59");

            CategoryPlot barPlot = barChartPanel.getChart().getCategoryPlot();
            barPlot.setDataset(barDataset);
        }

        // 3. 更新折线图
        if (lineChartPanel != null && stats.containsKey("subjectAverages")) {
            DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();
            @SuppressWarnings("unchecked")
            Map<String, Double> subjectAverages = (Map<String, Double>) stats.get("subjectAverages");

            // 按科目名称排序
            List<String> sortedSubjects = new ArrayList<>(subjectAverages.keySet());
            Collections.sort(sortedSubjects);

            for (String subject : sortedSubjects) {
                double avgScore = subjectAverages.get(subject);
                lineDataset.setValue(avgScore, "平均分", subject);
                System.out.println("Adding to line chart: " + subject + " = " + avgScore);
            }

            CategoryPlot linePlot = lineChartPanel.getChart().getCategoryPlot();
            linePlot.setDataset(lineDataset);

            // 设置X轴标签倾斜，以防文字重叠
            linePlot.getDomainAxis().setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
            );
        }
    }

    private void createClassTeacherTable() {
        System.out.println("Creating class teacher table...");

        // 创建动态列
        Vector<String> columnNames = new Vector<>();
        columnNames.add("学号");
        columnNames.add("姓名");

        // 添加所有科目列
        if (classSubjects != null && !classSubjects.isEmpty()) {
            for (Subject subject : classSubjects) {
                columnNames.add(subject.getSubjectName() + "(学分:" + subject.getCredits() + ")");
                System.out.println("Adding subject column: " + subject.getSubjectName());
            }
        } else {
            System.out.println("Warning: No subjects found for class teacher table");
        }

        // 添加统计列
        columnNames.add("平均分");
        columnNames.add("总分");
        columnNames.add("总学分");

        System.out.println("Creating table with " + columnNames.size() + " columns");

        // 使用 Vector 创建表格模型
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex >= 2 && columnIndex < getColumnCount() - 3) {
                    return Double.class; // 成绩列使用 Double 类型
                }
                return Object.class;
            }
        };

        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);

        // 设置表格列宽和对齐方式
        TableColumnModel columnModel = gradeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(100);  // 学号
        columnModel.getColumn(1).setPreferredWidth(80);   // 姓名

        // 设置其他列的宽度和对齐方式
        for (int i = 2; i < columnModel.getColumnCount(); i++) {
            columnModel.getColumn(i).setPreferredWidth(100);
            DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
            gradeTable.getColumnModel().getColumn(i).setCellRenderer(renderer);
        }

        // 打印列信息
        System.out.println("Table created with following columns:");
        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            System.out.println(i + ": " + tableModel.getColumnName(i));
        }
    }

    private void loadClassTeacherData() {
        if (tableModel == null) {
            System.out.println("Error: Table model is null");
            return;
        }

        System.out.println("Starting to load class teacher data...");
        System.out.println("Table column count: " + tableModel.getColumnCount());
        tableModel.setRowCount(0);
        Map<String, Object> filters = getFilters();

        // 首先获取班级所有学生
        List<StudentProfile> students = getClassStudents();
        System.out.println("Found " + students.size() + " students");

        // 获取班级所有成绩
        List<Grade> grades = gradeService.getClassGrades(currentUser.getId(), filters);
        System.out.println("Found " + grades.size() + " grades");

        // 按学生分组处理成绩
        Map<String, Map<String, Grade>> studentGrades = new HashMap<>();
        for (Grade grade : grades) {
            System.out.println("Processing grade: Student=" + grade.getStudentNo() +
                    ", Subject=" + grade.getSubjectName() +
                    ", Score=" + grade.getScore());
            studentGrades.computeIfAbsent(grade.getStudentNo(), k -> new HashMap<>())
                    .put(grade.getSubjectName(), grade);
        }

        // 统计数据
        int totalCount = students.size();
        int passCount = 0;
        int excellentCount = 0;
        int range90_100 = 0;
        int range80_89 = 0;
        int range70_79 = 0;
        int range60_69 = 0;
        int range0_59 = 0;

        // 计算各科目平均分
        Map<String, Double> subjectAverages = new HashMap<>();
        Map<String, Integer> subjectCounts = new HashMap<>();

        // 遍历所有成绩，计算每个科目的总分和人数
        for (Grade grade : grades) {
            String subjectName = grade.getSubjectName();
            subjectAverages.merge(subjectName, grade.getScore(), Double::sum);
            subjectCounts.merge(subjectName, 1, Integer::sum);
        }

        // 计算每个科目的平均分
        for (String subject : subjectAverages.keySet()) {
            double total = subjectAverages.get(subject);
            int count = subjectCounts.get(subject);
            subjectAverages.put(subject, total / count);
        }

        // 填充表格数据
        for (StudentProfile student : students) {
            List<Object> rowData = new ArrayList<>();
            String studentNo = student.getStudentNo();
            Map<String, Grade> subjectGrades = studentGrades.getOrDefault(studentNo, new HashMap<>());

            // 添加学号和姓名
            rowData.add(studentNo);
            rowData.add(student.getName());

            // 计算统计数据
            double totalScore = 0;
            double totalCredits = 0;
            int validSubjectCount = 0;

            // 添加各科成绩
            if (classSubjects != null && !classSubjects.isEmpty()) {
                for (Subject subject : classSubjects) {
                    Grade grade = subjectGrades.get(subject.getSubjectName());
                    if (grade != null) {
                        double score = grade.getScore();
                        rowData.add(score);
                        totalScore += score;
                        validSubjectCount++;

                        // 统计成绩分布
                        if (score >= 90) {
                            range90_100++;
                            excellentCount++;
                            passCount++;
                        } else if (score >= 80) {
                            range80_89++;
                            passCount++;
                        } else if (score >= 70) {
                            range70_79++;
                            passCount++;
                        } else if (score >= 60) {
                            range60_69++;
                            passCount++;
                        } else {
                            range0_59++;
                        }

                        // 只有及格的成绩才计入学分
                        if (score >= 60) {
                            totalCredits += subject.getCredits();
                        }
                    } else {
                        rowData.add("-");
                    }
                }
            }

            // 添加统计数据
            double avgScore = validSubjectCount > 0 ? totalScore / validSubjectCount : 0;
            rowData.add(String.format("%.2f", avgScore));
            rowData.add(String.format("%.2f", totalScore));
            rowData.add(String.format("%.2f", totalCredits));

            tableModel.addRow(rowData.toArray());
        }

        // 更新统计数据
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", totalCount);
        stats.put("passCount", passCount);
        stats.put("excellentCount", excellentCount);
        stats.put("range_90_100", range90_100);
        stats.put("range_80_89", range80_89);
        stats.put("range_70_79", range70_79);
        stats.put("range_60_69", range60_69);
        stats.put("range_0_59", range0_59);

        // 添加各科平均分数据
        stats.put("subjectAverages", subjectAverages);

        // 计算及格率和优秀率
        double passRate = totalCount > 0 ? (passCount * 100.0 / totalCount) : 0;
        double excellentRate = totalCount > 0 ? (excellentCount * 100.0 / totalCount) : 0;
        stats.put("passRate", passRate);
        stats.put("excellentRate", excellentRate);

        // 更新图表
        updateCharts(stats);

        System.out.println("Subject Averages:");
        subjectAverages.forEach((subject, avg) ->
                System.out.println(subject + ": " + avg)
        );

        System.out.println("Finished loading class teacher data");
    }

    private List<StudentProfile> getClassStudents() {
        List<StudentProfile> students = new ArrayList<>();
        String sql = "SELECT u.username as student_no, u.name " +
                "FROM students s " +
                "JOIN users u ON s.user_id = u.id " +
                "JOIN classes c ON s.class_id = c.id " +
                "WHERE c.teacher_id = ? " +
                "ORDER BY u.username";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, currentUser.getId());
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                StudentProfile student = new StudentProfile();
                student.setStudentNo(rs.getString("student_no"));
                student.setName(rs.getString("name"));
                students.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return students;
    }

    private void createNormalTable() {
        // 创建普通教师的表格列
        String[] columnNames = {
                "学号", "姓名", "班级", "科目", "成绩", "排名", "平均分", "考试类型", "考试日期"
        };

        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);

        // 设置表格列宽
        TableColumnModel columnModel = gradeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(100);  // 学号
        columnModel.getColumn(1).setPreferredWidth(80);   // 姓名
        columnModel.getColumn(2).setPreferredWidth(100);  // 班级
        columnModel.getColumn(3).setPreferredWidth(100);  // 科目
        columnModel.getColumn(4).setPreferredWidth(60);   // 成绩
        columnModel.getColumn(5).setPreferredWidth(60);   // 排名
        columnModel.getColumn(6).setPreferredWidth(60);   // 平均分
        columnModel.getColumn(7).setPreferredWidth(100);  // 考试类型
        columnModel.getColumn(8).setPreferredWidth(100);  // 考试日期
    }

    private void loadNormalData() {
        Map<String, Object> filters = getFilters();
        String sortMethod = (String) sortComboBox.getSelectedItem();
        String orderBy = null;

        if (sortMethod != null) {
            switch (sortMethod) {
                case "成绩升序":
                    orderBy = "score_asc";
                    break;
                case "成绩降序":
                    orderBy = "score_desc";
                    break;
                case "排名升序":
                    orderBy = "rank_asc";
                    break;
                case "排名降序":
                    orderBy = "rank_desc";
                    break;
            }
        }

        loadGradeData(filters, orderBy);
    }

    private Map<String, Object> getFilters() {
        Map<String, Object> filters = new HashMap<>();

        // 获取班级ID
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass != null && !selectedClass.equals("全部班级")) {
            filters.put("classId", classIdMap.get(selectedClass));
        }

        // 获取考试类型
        String examType = (String) examTypeComboBox.getSelectedItem();
        if (examType != null && !examType.equals("全部")) {
            filters.put("examType", examType);
        }

        // 获取考试日期
        if (examDateChooser.getDate() != null) {
            filters.put("examDate", new java.sql.Date(examDateChooser.getDate().getTime()));
        }

        // 获取搜索关键词
        String search = searchField.getText().trim();
        if (!search.isEmpty()) {
            filters.put("search", search);
        }

        // 如果是普通教师，添加教师ID筛选
        if (!isClassTeacher) {
            filters.put("teacherId", currentUser.getId());
        }

        return filters;
    }

    private void updateStatsLabels(Map<String, Object> stats) {
        if (!isClassTeacher || statsPanel == null || stats == null) return;

        // 获取统计信息，添加默认值
        int totalCount = stats.containsKey("totalCount") ? ((Number) stats.get("totalCount")).intValue() : 0;
        double avgScore = stats.containsKey("avgScore") ? ((Number) stats.get("avgScore")).doubleValue() : 0.0;
        double passRate = stats.containsKey("passRate") ? ((Number) stats.get("passRate")).doubleValue() : 0.0;
        double excellentRate = stats.containsKey("excellentRate") ? ((Number) stats.get("excellentRate")).doubleValue() : 0.0;

        // 更新标签文本
        ((JLabel) statsPanel.getComponent(0)).setText(String.format("总人数: %d人", totalCount));
        ((JLabel) statsPanel.getComponent(1)).setText(String.format("班级平均分: %.2f", avgScore));
        ((JLabel) statsPanel.getComponent(2)).setText(String.format("及格率: %.2f%%", passRate));
        ((JLabel) statsPanel.getComponent(3)).setText(String.format("优秀率: %.2f%%", excellentRate));
    }

    private JPanel createClassTeacherPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 创建班级成绩表格面板
        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(),
                "班级成绩总览",
                TitledBorder.LEFT, TitledBorder.TOP, TITLE_FONT
        ));

        // 先创建表格
        createClassTeacherTable();

        // 创建统计信息面板
        statsPanel = new JPanel(new GridLayout(1, 4, 10, 0));
        statsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // 添加统计标签
        JLabel totalStudentsLabel = new JLabel("总人数: 0人");
        JLabel avgScoreLabel = new JLabel("班级平均分: 0.00");
        JLabel passRateLabel = new JLabel("及格率: 0.00%");
        JLabel excellentRateLabel = new JLabel("优秀率: 0.00%");

        // 设置字体
        totalStudentsLabel.setFont(CONTENT_FONT);
        avgScoreLabel.setFont(CONTENT_FONT);
        passRateLabel.setFont(CONTENT_FONT);
        excellentRateLabel.setFont(CONTENT_FONT);

        // 添加到统计面板
        statsPanel.add(totalStudentsLabel);
        statsPanel.add(avgScoreLabel);
        statsPanel.add(passRateLabel);
        statsPanel.add(excellentRateLabel);

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(gradeTable);
        scrollPane.setPreferredSize(new Dimension(0, 400));

        // 添加到表格面板
        tablePanel.add(scrollPane, BorderLayout.CENTER);
        tablePanel.add(statsPanel, BorderLayout.SOUTH);

        // 添加到主面板
        panel.add(tablePanel, BorderLayout.CENTER);

        // 修改图表面板为网格布局
        JPanel chartPanel = new JPanel(new GridLayout(1, 3, 10, 0));
        chartPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(),
                "班级成绩分析",
                TitledBorder.LEFT, TitledBorder.TOP, TITLE_FONT
        ));

        // 1. 成绩等级分布饼图
        JPanel piePanel = new JPanel(new BorderLayout());
        pieChartPanel = createPieChartPanel();
        piePanel.add(pieChartPanel, BorderLayout.CENTER);
        chartPanel.add(piePanel);

        // 2. 成绩分布柱状图
        JPanel barPanel = new JPanel(new BorderLayout());
        barChartPanel = createBarChartPanel();
        barPanel.add(barChartPanel, BorderLayout.CENTER);
        chartPanel.add(barPanel);

        // 3. 各科平均分对比图
        JPanel linePanel = new JPanel(new BorderLayout());
        lineChartPanel = createLineChartPanel();
        linePanel.add(lineChartPanel, BorderLayout.CENTER);
        chartPanel.add(linePanel);

        panel.add(chartPanel, BorderLayout.SOUTH);

        // 立即加载数据
        loadClassTeacherData();

        return panel;
    }

    private ChartPanel createBarChartPanel() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        JFreeChart chart = ChartFactory.createBarChart(
                "成绩分布",          // 图表标题
                "分数段",           // X轴标签
                "人数",            // Y轴标签
                dataset,
                PlotOrientation.VERTICAL,
                true,             // 显示图例
                true,             // 显示工具提示
                false             // 不生成URL
        );

        // 设置图表样式
        chart.setTitle(new TextTitle("成绩分布", new Font("微软雅黑", Font.BOLD, 14)));
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.GRAY);
        plot.setRangeGridlinePaint(Color.GRAY);

        // 设置字体
        plot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getRangeAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(300, 300));
        return chartPanel;
    }

    private ChartPanel createLineChartPanel() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        JFreeChart chart = ChartFactory.createLineChart(
                "各科平均分对比",    // 图表标题
                "科目",           // X轴标签
                "平均分",         // Y轴标签
                dataset,
                PlotOrientation.VERTICAL,
                true,            // 显示图例
                true,            // 显示工具提示
                false            // 不生成URL
        );

        // 设置图表样式
        chart.setTitle(new TextTitle("各科平均分对比", new Font("微软雅黑", Font.BOLD, 14)));
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.GRAY);
        plot.setRangeGridlinePaint(Color.GRAY);

        // 设置字体
        plot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getRangeAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 设置Y轴范围为0-100
        plot.getRangeAxis().setRange(0, 100);

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(300, 300));
        return chartPanel;
    }

    private JPanel createTeacherPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 创建任教成绩表格面板
        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(),
                "任教成绩列表",
                TitledBorder.LEFT, TitledBorder.TOP, TITLE_FONT
        ));

        createNormalTable();
        JScrollPane scrollPane = new JScrollPane(gradeTable);
        scrollPane.setPreferredSize(new Dimension(0, 400));
        tablePanel.add(scrollPane, BorderLayout.CENTER);

        panel.add(tablePanel, BorderLayout.CENTER);

        // 添加图表面板
        JPanel chartPanel = new JPanel(new BorderLayout());
        chartPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(),
                "成绩分析",
                TitledBorder.LEFT, TitledBorder.TOP, TITLE_FONT
        ));

        pieChartPanel = createPieChartPanel();
        chartPanel.add(pieChartPanel, BorderLayout.CENTER);

        panel.add(chartPanel, BorderLayout.SOUTH);
        return panel;
    }
}